<script setup lang="ts">
import { onMounted, onUnmounted, defineProps, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

interface Activity {
  id: number;
  name: string;
  location: {
    longitude: number;
    latitude: number;
  };
  description: string;
  isCheckIn: boolean;
  dis?: number;
}

let map: any = null; // 不需要 ref

// 接收父组件传递的 address 和 activity
const props = defineProps<{
  address: [number, number];
  activity: Activity[];
}>();
const markers = ref<any[]>([]); // 保证 markers 是响应式的
const emit = defineEmits<{
  (e: 'update', activity: Activity): void;
}>();

// 添加一个方法来处理标记的更新
const updateMarkers = (AMap: any) => {
  console.log('开始更新标记');
  // 清除现有的标记
  markers.value.forEach(marker => {
    map.remove(marker);
  });
  markers.value = [];

  // 添加新的活动地点标记
  props.activity.forEach((activity) => {
    console.log('更新活动标记：', activity);
    const activityMarker = new AMap.Marker({
      position: new AMap.LngLat(activity.location.longitude, activity.location.latitude),
      title: activity.description,
      label: {
        content: activity.name
      }
    });

    // 将活动标记添加到地图
    map.add(activityMarker);
    markers.value.push(activityMarker);

    // 子传父事件
    activityMarker.on("click", () => {
      emit('update', {
        ...activity,
        dis: AMap.GeometryUtil.distance(
          [activity.location.longitude, activity.location.latitude], 
          props.address
        )
      });
    });
  });
};

let AMapInstance: any = null;
const key = ''
onMounted(() => {
	if(key === ''){
		alert("请配置高德的key")
		return;
	}
  AMapLoader.load({
    key: key,
    version: "2.0",
    plugins: ["AMap.Scale"],
  })
    .then((AMap) => {
      AMapInstance = AMap; // 保存 AMap 实例
      // 创建地图实例
      map = new AMap.Map("container", {
        viewMode: "3D",
        zoom: 9,
        center: props.address,
      });

      // 初始化标记
      updateMarkers(AMap);
    })
    .catch((e) => {
      console.log(e);
    });
});

// 监听 activity 的变化
watch(
  () => props.activity,
  (newVal) => {
    console.log('活动数据更新：', newVal);
    if (map && AMapInstance) {
      updateMarkers(AMapInstance);
    }
  },
  { deep: true } // 深度监听数组变化
);

// 监听 address 的变化
watch(
  () => props.address,
  (newVal) => {
    if (map) {
      map.setCenter(newVal);
    }
  }
);

onUnmounted(() => {
  map?.destroy();
});
</script>

<template>
  <div id="container"></div>
</template>

<style scoped>
#container {
  width: 100%;
  height: auto;
}
</style>
